/*
 * FormDisciplina.java
 *
 * Created on 4 de Novembro de 2008, 20:10
 */
package br.com.radaction.gui;

import br.com.radaction.DAO.CursoDAO;
import br.com.radaction.DAO.DisciplinaDAO;
import br.com.radaction.DTO.Curso;
import br.com.radaction.DTO.Disciplina;
import java.sql.SQLException;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/**
 * Esta Classe é uma implementação GUI para mostrar as disciplinas cadastradas pelo aluno
 * @author  robson
 */
public class FormDisciplina extends javax.swing.JInternalFrame {

    private JFrame mdi;

    /** Construtor, cria um novo formulário FormDisciplina */
    public FormDisciplina(JFrame mdi) {
        this.mdi = mdi;
        initComponents();        
    }

     /**
     * Este método atualiza a grade de disciplinas
     * É um método sem retorno
     */
    private void atualizaLista() {
        try {
            DisciplinaDAO disciplinaDAO = new DisciplinaDAO(MDIAcademics.getConexao());
            List<Disciplina> lista = disciplinaDAO.listaTodos();
            DefaultTableModel dtm = (DefaultTableModel) this.tbDisciplina.getModel();
            dtm.setRowCount(0);
            for (Disciplina disciplina : lista) {
                dtm.addRow(new Object[]{disciplina.getCod(), disciplina.getNome(), disciplina.getCurso()});
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao ler as Disciplinas:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(FormDisciplina.class.getName()).log(Level.WARNING, "Erro ao ler as Avaliacoes", ex);
        }
    }
    
    /**
     * Método auxiliar para converter valores String sem causar exceções.
     * @param valor String contendo o valor a ser transformado para número
     * @return O valor convertido em inteiro ou zero em caso de algum problema
     */
    private int intCampoTelas(String valor) {
        int ret = 0;
        try {
            ret = Integer.parseInt(valor);
        } catch (NumberFormatException ex) {
        }
        return ret;
    }
    
     /**
     * Método auxiliar que limpa todos os campos da GUI
     */
    private void limpaTela() {
        this.txtCodigo.setText(null);
        this.txtNomeDisciplina.setText(null);
        this.cmbCurso.setSelectedIndex(0);
        this.txtObsDisciplina.setText(null);
        this.txtNomeDisciplina.requestFocus();
    }

     /**
     * Método que busca através do DAO os cursos no banco de dados e
     * carrega no ComboBox
     * É um método sem retorno
     */
    private void carregaCmbCurso() {
        try {
            CursoDAO cursoDAO = new CursoDAO(MDIAcademics.getConexao());
            List<Curso> lista = cursoDAO.listaTodos();
            Vector v = new Vector(lista);
            v.add(0, "");
            ComboBoxModel cbm = new DefaultComboBoxModel(v);
            this.cmbCurso.setModel(cbm);
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao ler as Avaliacoes:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(FormAvaliacao.class.getName()).log(Level.WARNING, "Erro ao ler as Avaliacoes", ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtObsDisciplina = new javax.swing.JTextArea();
        cmbCurso = new javax.swing.JComboBox();
        txtNomeDisciplina = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbDisciplina = new javax.swing.JTable();
        btSalva = new javax.swing.JButton();
        btLimpa = new javax.swing.JButton();
        btExclui = new javax.swing.JButton();
        btAtualiza = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Cadastro de Disciplinas");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameDeiconified(evt);
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Preencha os dados"));

        jLabel1.setText("Nome:");

        jLabel2.setText("Curso:");

        jLabel3.setText("Observações:");

        txtObsDisciplina.setColumns(20);
        txtObsDisciplina.setLineWrap(true);
        txtObsDisciplina.setRows(5);
        txtObsDisciplina.setToolTipText("Observações");
        txtObsDisciplina.setWrapStyleWord(true);
        jScrollPane1.setViewportView(txtObsDisciplina);

        cmbCurso.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbCurso.setToolTipText("Selecione o curso");

        txtNomeDisciplina.setToolTipText("Nome da disciplina");

        jLabel4.setText("Código:");

        txtCodigo.setToolTipText("Código automático");
        txtCodigo.setEnabled(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2))
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE)
                    .addComponent(cmbCurso, 0, 437, Short.MAX_VALUE)
                    .addComponent(txtNomeDisciplina, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtNomeDisciplina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cmbCurso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(55, 55, 55))
        );

        tbDisciplina.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cod.", "Nome", "Curso"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbDisciplina.getTableHeader().setReorderingAllowed(false);
        tbDisciplina.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbDisciplinaMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tbDisciplina);
        tbDisciplina.getColumnModel().getColumn(0).setMinWidth(40);
        tbDisciplina.getColumnModel().getColumn(0).setPreferredWidth(40);
        tbDisciplina.getColumnModel().getColumn(0).setMaxWidth(40);

        btSalva.setText("Salvar");
        btSalva.setToolTipText("Salvar registro");
        btSalva.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvaActionPerformed(evt);
            }
        });

        btLimpa.setText("Limpar");
        btLimpa.setToolTipText("Limpar campos");
        btLimpa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLimpaActionPerformed(evt);
            }
        });

        btExclui.setText("Excluir");
        btExclui.setToolTipText("Excluir registro");
        btExclui.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btExcluiActionPerformed(evt);
            }
        });

        btAtualiza.setText("Atualizar");
        btAtualiza.setToolTipText("Atualizar lista de disciplinas");
        btAtualiza.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAtualizaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 572, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btSalva)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btLimpa)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btExclui)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 331, Short.MAX_VALUE)
                        .addComponent(btAtualiza)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btSalva)
                    .addComponent(btLimpa)
                    .addComponent(btExclui)
                    .addComponent(btAtualiza))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

     /**
     * Preenche os campos da tela com informações das disciplinas.
     * @param disciplina Disciplina que irá fornecer o código para pesquisa no SGBD e em seguida ir para a tela.
     */
    private void preencheTela(Disciplina disciplina) {
        try {
            DisciplinaDAO disciplinaDAO = new DisciplinaDAO(MDIAcademics.getConexao());
            disciplina = disciplinaDAO.retrieve(disciplina);
            if (disciplina != null && disciplina.getCod() > 0) {
                this.txtCodigo.setText(Integer.toString(disciplina.getCod()));
                this.txtNomeDisciplina.setText(disciplina.getNome());
                this.cmbCurso.setSelectedItem(disciplina.getCurso());
                this.txtObsDisciplina.setText(disciplina.getObservacao());
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this.mdi, String.format("Não foi possível carregar Disciplinas: %s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(FormDisciplina.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

private void tbDisciplinaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbDisciplinaMouseClicked
    if (evt.getClickCount() > 0) {
        JTable obj = (JTable) evt.getComponent();
        int linha = obj.getSelectedRow();
        Integer cod = (Integer) obj.getModel().getValueAt(linha, 0);
        Disciplina disciplina = new Disciplina(cod);
        this.preencheTela(disciplina);
    }
}//GEN-LAST:event_tbDisciplinaMouseClicked

private void btSalvaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvaActionPerformed
    try {
        Disciplina disciplina = new Disciplina();
        Object obj = this.cmbCurso.getModel().getSelectedItem();
        //abaixo o Object obj é testado se é um objeto Disciplina, se for é 
        //setado para disciplina Disciplina
        if (obj instanceof Curso) {
            disciplina.setCurso((Curso) obj);
        } else {
            JOptionPane.showMessageDialog(this.mdi, "Curso não informado!");
            this.cmbCurso.requestFocus();
            return;
        }
        disciplina.setNome(txtNomeDisciplina.getText().toUpperCase());
        disciplina.setObservacao(txtObsDisciplina.getText().toUpperCase());
        DisciplinaDAO disciplinaDAO = new DisciplinaDAO(MDIAcademics.getConexao());
        int cod = this.intCampoTelas(this.txtCodigo.getText());
        // Escolhe entre atualizar ou criar!
        if (cod > 0) {
            disciplina.setCod(cod);
            disciplinaDAO.update(disciplina);
        } else {
            disciplinaDAO.create(disciplina);
            this.txtCodigo.setText(Integer.toString(disciplina.getCod()));
        }

        JOptionPane.showMessageDialog(this.mdi, "Registro Salvo");
        this.limpaTela();
        this.carregaCmbCurso();
        this.atualizaLista();
    } catch (NumberFormatException ex) {
        JOptionPane.showMessageDialog(this.mdi, "Número mal formatado [Código]");
        this.txtCodigo.requestFocus();
    } catch (SQLException ex) {
        JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao gravar Disciplina:%s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(FormDisciplina.class.getName()).log(Level.SEVERE, null, ex);
    }

}//GEN-LAST:event_btSalvaActionPerformed

private void btLimpaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLimpaActionPerformed
    this.limpaTela();
    this.atualizaLista();
}//GEN-LAST:event_btLimpaActionPerformed

private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
    this.atualizaLista();
    this.carregaCmbCurso();
}//GEN-LAST:event_formInternalFrameOpened

private void btExcluiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btExcluiActionPerformed
    try{
    Disciplina disciplina = new Disciplina(Integer.parseInt(this.txtCodigo.getText()));
    DisciplinaDAO disciplinaDAO = new DisciplinaDAO(MDIAcademics.getConexao());
    disciplinaDAO.delete(disciplina);
    }catch(NumberFormatException nfe){
        JOptionPane.showMessageDialog(this.mdi, "Número mal formatado [Código]\n" +
                                                "Selecione algum item da lista");
        this.txtCodigo.requestFocus();
    }catch(SQLException ex){
        JOptionPane.showMessageDialog(this.mdi, String.format("Erro ao deletar Disciplina:%s", ex.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE));
        Logger.getLogger(FormDisciplina.class.getName()).log(Level.SEVERE, null, ex);
    }
    this.limpaTela();
    this.atualizaLista();
}//GEN-LAST:event_btExcluiActionPerformed

private void btAtualizaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAtualizaActionPerformed
    this.atualizaLista();
    this.carregaCmbCurso();
    this.limpaTela();
}//GEN-LAST:event_btAtualizaActionPerformed

private void formInternalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameDeiconified
    this.atualizaLista();
    this.carregaCmbCurso();
}//GEN-LAST:event_formInternalFrameDeiconified

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAtualiza;
    private javax.swing.JButton btExclui;
    private javax.swing.JButton btLimpa;
    private javax.swing.JButton btSalva;
    private javax.swing.JComboBox cmbCurso;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tbDisciplina;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtNomeDisciplina;
    private javax.swing.JTextArea txtObsDisciplina;
    // End of variables declaration//GEN-END:variables
}
